package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.my.adapter.CashRecordAdapter;
import com.example.lenovo.asia5b.my.bean.CashRecordBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * 取现记录列表
 * Created by lenovo on 2017/7/1.
 */

public class CashRecordActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener{
    private  ListView lv_record_top_up;
    private CashRecordAdapter adapter;
    private LoadingDalog loadingDalog;
    private int page  = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private List<CashRecordBean> lists = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_top_up);
        initView();
        recordData();
    }
    public void initView() {
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.cash_record));
        pullToRefreshLayout = ((PullToRefreshLayout)findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(public_btn_left).clicked(this);
        lv_record_top_up = (ListView)findViewById(R.id.lv_record_top_up);
        adapter = new CashRecordAdapter(this);
        lv_record_top_up.setAdapter(adapter);
        lv_record_top_up.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(CashRecordActivity.this,CashRecordDetActivity.class);
                intent.putExtra("id",adapter.getLists().get(i).id);
                startActivity(intent);
            }
        });
        lv_record_top_up.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            recordData();
                        } else {
                            TextView load_tv = (TextView)findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            default:
                break;
        }
    }


    /**
     * 充值或者取现接口
     */
    public void recordData() {
        try {
            int typeId = 2;
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.CZ_DIARY;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"page"+page,"type"+typeId,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("page",""+page);
            parmaMap.put("type",""+typeId);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }
    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        recordData();
    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (null != result && result instanceof JSONObject) {
                try {
                    JSONObject json =  (JSONObject)result;
                    int state = (int)json.getInt("State");
                    if (state == 0) {
                        JSONObject paging = json.getJSONObject("paging");
                        if (null!=paging.getString("page") && "1".equals(paging.getString("page"))) {
                            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                            initPaging(paging);
                            JSONArray account = json.getJSONArray("account");
                            lists = Logic.getListToBean(account,new CashRecordBean());
                            adapter.setLists(lists);
                            adapter.notifyDataSetChanged();

                        } else if(null!=paging.getString("page") && !"1".equals(paging.getString("page"))){
                            pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                            JSONArray account = (JSONArray) json.get("account");
                            if (null != account && account.length() > 0) {
                                List<CashRecordBean> listBean  =  Logic.getListToBean(account,new CashRecordBean());
                                for (int i = 0; i < listBean.size(); i++) {
                                    lists .add(listBean.get(i));
                                }
                                adapter .setLists(lists);
                                adapter .notifyDataSetChanged();
                            } else {
                                page = page - 1;
                            }

                        }
                    }  else if(state == 1){
                        U.Toast(CashRecordActivity.this,getResources().getString(R.string.qmsb));
                    }else if(state == 2){
                        U.Toast(CashRecordActivity.this,getResources().getString(R.string.cscw)
                        );
                    }else if(state == 3){
                        U.Toast(CashRecordActivity.this,getResources().getString(R.string.wdl));
                    }else if(state == 4){
                        U.Toast(CashRecordActivity.this,getResources().getString(R.string.mysj)
                        );
                    }
                } catch (Exception e) {
                }
            }
            loadingDalog.dismiss();
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        }

    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);

    }


    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <=1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }
}
